package cascade.components
{
	import cascade.model.Page;
	
	import flash.desktop.Clipboard;
	import flash.desktop.ClipboardFormats;
	import flash.desktop.NativeDragActions;
	import flash.desktop.NativeDragManager;
	import flash.events.Event;
	import flash.events.NativeDragEvent;
	
	import mx.collections.ArrayCollection;
	import mx.events.DragEvent;
	import mx.events.TreeEvent;
	

	public class SiteTree extends NodeTree
	{
		[Embed("/assets/icons/file_new-16.png")]
		public var iconBlankPage:Class;
		[Embed("/assets/icons/file_redirect-16.png")]
		public var iconRedirectPage:Class;
		protected var cachedOpenItems:Array;
		
		
		public function SiteTree()
		{
			Cascade.model.bindSetter(this, onRefresh, "siteTree");
			addEventListener(TreeEvent.ITEM_OPEN, saveOpenPages);
			addEventListener(TreeEvent.ITEM_CLOSE, saveOpenPages);
			dataTipFunction = getPageDataTip;
		}
		
		
		
		/**
		 * Caches the open pages so that they may be restored after a refresh
		 * or after the application restarts
		 */
		protected function saveOpenPages(event:Event):void {
			cachedOpenItems = new Array();
			
			for each (var page:Page in openItems)
				cachedOpenItems.push(page.id);
		}
		
		/**
		 * When the tree is refreshed we need to set open items to open again
		 */
		protected function onRefresh(siteTree:ArrayCollection):void {
			
			// fix opened items
			var opened:Array = new Array();
			
			for each (var id:uint in cachedOpenItems)
				opened.push(Page.getPageById(id));
			
			openItems = opened;
			
			if (dataProvider != null && !openItems.length && dataProvider.length)
			{
				expandItem(dataProvider[0], true);
				if (!Cascade.view.selectedPage)
					Cascade.controller.execCommand("selectPage", dataProvider[0]);
			}
			
			if (Cascade.view.selectedPage) {
				id = Cascade.view.selectedPage.id;
				callLater(function():void {
					Cascade.view.selectedPage = Page.getPageById(id);
				});
			}
		}
		
		protected override function dragStartHandler(event:DragEvent):void
		{
			super.dragStartHandler(event);
//			var clipboard:Clipboard = new Clipboard();
//			var page:Page = selectedItem as Page;
//			clipboard.setData(ClipboardFormats.TEXT_FORMAT, page.name);
//			//clipboard.setData("page", page);
//			NativeDragManager.doDrag(this, clipboard);
		}
		
		///// FORMATTERS /////
		
		public override function itemToIcon(item:Object):Class
		{
			var page:Page = item as Page;
			if (page == null)
				return null;
			
			if (page.redirect_id)
				return iconRedirectPage;
			
			return iconBlankPage;
		}
		
		protected function getPageDataTip(page:Page):String {
			return page.relativePath;
		}
	}
}